package com.ai.sevice.ai;

import com.ai.common.RefObject;
import com.ai.common.email.EmailClient;
import com.ai.common.enums.ConfigModuleEnum;
import com.ai.common.http.WeiXinApiClient;
import com.ai.common.http.dto.WXOpenIdResponse;
import com.ai.common.utils.CommonUtil;
import com.ai.common.utils.ConfigUtil;
import com.ai.common.utils.ConvertUtil;
import com.ai.common.utils.IdUtil;
import com.ai.dao.entity.FeedbackSuggest;
import com.ai.dao.entity.ai.AiUser;
import com.ai.dao.entity.ai.AiUserSignIn;
import com.ai.repository.FeedbackSuggestRepository;
import com.ai.repository.ai.AiUserRepository;
import com.ai.repository.ai.AiUserSignInRepository;
import com.ai.sevice.ai.request.FeedbackRequest;
import com.ai.sevice.ai.request.LoginRequest;
import com.ai.sevice.ai.request.ShareRequest;
import com.ai.sevice.ai.response.*;
import com.ai.sevice.ai.response.dto.GetCurDateUserDto;
import com.ai.sevice.ai.response.dto.SignInDto;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service
public class UserService {

    @Autowired
    private AiUserRepository aiUserRepository;

    @Autowired
    private WeiXinApiClient weiXinApiClient;

    @Autowired
    private EmailClient emailClient;

    @Autowired
    private FeedbackSuggestRepository feedbackSuggestRepository;

    @Autowired
    private AiUserSignInRepository aiUserSignInRepository;

    @Autowired
    private RedissonClient redissonClient;

    /**
     * 分享
     * @param request
     * @return
     */
    public synchronized ShareResponse share(ShareRequest request) {
        ShareResponse response = new ShareResponse();
        if (StringUtils.isBlank(request.getWxCode()) || StringUtils.isBlank(request.getUid())){
            response.setCode(1);
            response.setMsg("请求参数异常");
            return response;
        }
        String shareUid = request.getUid();
        WXOpenIdResponse wxOpenIdResponse = weiXinApiClient.getWxOpenId(request.getWxCode());
        if (wxOpenIdResponse == null || StringUtils.isBlank(wxOpenIdResponse.getOpenid())){
            response.setCode(1);
            response.setMsg("获取uid失败");
            return response;
        }
        AiUser aiUser = aiUserRepository.getUserByOpenId(wxOpenIdResponse.getOpenid());
        if (aiUser != null){
            response.setUid(aiUser.getUid());
        }else{
            //新用户
            String uid = insertAiUser(wxOpenIdResponse.getOpenid(),shareUid);
            if (StringUtils.isNotBlank(uid)){
                response.setUid(uid);
                AiUser shareUser = aiUserRepository.getUserByUid(shareUid);
                if (shareUser != null){
                    //给分享用户新增积分
                    int integral = 20;
                    String shareAdd = ConfigUtil.getInstance().getConfig(ConfigModuleEnum.integral.getModule(), "shareAdd");
                    if (StringUtils.isNotBlank(shareAdd)){
                        integral = Integer.parseInt(shareAdd);
                    }
                    shareUser.setIntegral(shareUser.getIntegral() + integral);

                    String cardList = shareUser.getCardList();
                    if (!"all".equals(cardList)) {
                        //给分享者解锁卡片
                        String privateCardListStr = ConfigUtil.getInstance().getConfig(ConfigModuleEnum.aiCard.getModule(), "privateCardList");
                        if (StringUtils.isNotBlank(privateCardListStr)) {
                            List<String> privateCardList = Arrays.asList(privateCardListStr.split(","));
                            if (StringUtils.isBlank(cardList)){
                                shareUser.setCardList(privateCardList.get(0));
                            }else{
                                List<String> userCardList = new ArrayList<>(Arrays.asList(cardList.split(",")));
                                for (String privateCard : privateCardList){
                                    if (!userCardList.contains(privateCard)){
                                        userCardList.add(privateCard);
                                        break;
                                    }
                                }
                                shareUser.setCardList(String.join(",", userCardList));
                            }
                        }
                    }
                    int shareUpdate = aiUserRepository.updateByPrimaryKeySelective(shareUser);
                    if (shareUpdate <= 0){
                        log.warn("分享更新权益失败 -> " + JSON.toJSONString(request));
                    }
                }
            }else{
                response.setCode(1);
                response.setMsg("网络异常，请稍后重试！");
            }
        }
        return response;
    }

    /**
     * 获取分享信息
     * @return
     */
    public GetShareInfoResponse getShareInfo() {
        GetShareInfoResponse response = new GetShareInfoResponse();
        String homeTitle = ConfigUtil.getInstance().getConfig(ConfigModuleEnum.share.getModule(), "homeTitle");
        String imageUrl = ConfigUtil.getInstance().getConfig(ConfigModuleEnum.share.getModule(), "imageUrl");
        response.setTitle(homeTitle);
        response.setImageUrl(imageUrl);
        return response;
    }

    /**
     * 根据微信code获取用户信息
     * @param wxCode
     * @return
     */
    public synchronized GetUserByWXCodeResponse getUserByWXCode(String wxCode) {
        GetUserByWXCodeResponse response = new GetUserByWXCodeResponse();
        WXOpenIdResponse wxOpenIdResponse = weiXinApiClient.getWxOpenId(wxCode);
        if (wxOpenIdResponse == null || StringUtils.isBlank(wxOpenIdResponse.getOpenid())){
            response.setCode(1);
            response.setMsg("获取uid失败");
            return response;
        }
        AiUser aiUser = aiUserRepository.getUserByOpenId(wxOpenIdResponse.getOpenid());
        if (aiUser != null){
            response.setUid(aiUser.getUid());
        }else{
            String uid = insertAiUser(wxOpenIdResponse.getOpenid(),null);
            if (StringUtils.isNotBlank(uid)){
                response.setUid(uid);
            }else{
                response.setCode(1);
                response.setMsg("网络异常，请稍后重试！");
            }
            return response;
        }
        return response;
    }

    private String insertAiUser(String openid,String shareUid) {
        String uid = null;
        for (int i = 0; i < 10; i++) {
            uid = IdUtil.getRandomString(8);
            AiUser userByUid = aiUserRepository.getUserByUid(uid);
            if (userByUid == null && StringUtils.isNotBlank(uid)){
                break;
            }
            uid = null;
        }
        if (StringUtils.isBlank(uid)){
            return null;
        }
        AiUser aiUserInsert = new AiUser();
        aiUserInsert.setUid(uid);
        aiUserInsert.setOpenId(openid);
        aiUserInsert.setShareUid(shareUid);
        String userName = ConfigUtil.getInstance().getConfig(ConfigModuleEnum.DEFAULT.getModule(), "userName");
        aiUserInsert.setName(userName);
        int integral = 100;
        String integralInitialize = ConfigUtil.getInstance().getConfig(ConfigModuleEnum.integral.getModule(), "initialize");
        if (StringUtils.isNotBlank(integralInitialize)){
            integral = Integer.parseInt(integralInitialize);
        }
        aiUserInsert.setIntegral(integral);
        int insert = aiUserRepository.insertSelective(aiUserInsert);
        if (insert > 0){
            return uid;
        }
        return null;
    }

    /**
     * 根据uid获取用户信息
     * @param uid
     * @return
     */
    public GetUserByUidResponse getUserByUid(String uid) {
        GetUserByUidResponse response = null;
        try {
            AiUser aiUser = aiUserRepository.getUserByUid(uid);
            response = ConvertUtil.convert(aiUser, GetUserByUidResponse.class);
            setUserByUidResponse(response,aiUser);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        }
        if (response == null){
            response = new GetUserByUidResponse();
        }
        return response;
    }

//    /**
//     * 根据uid获取用户信息
//     * @param uid
//     * @return
//     */
//    public GetUserByUidResponse getUserByUid(String uid) {
//        GetUserByUidResponse response = null;
//        try {
//            AiUser aiUser = TimeExpiredPoolCache.getInstance().get(uid);
//            if (aiUser != null){
//                response = ConvertUtil.convert(aiUser, GetUserByUidResponse.class);
//                response.setMsg("使用缓存");
//                setUserByUidResponse(response,aiUser);
//                return response;
//            }
//
//            AiUser userByUid = aiUserRepository.getUserByUid(uid);
//
//            if (userByUid != null){
//                // 设置失效时间10秒
//                TimeExpiredPoolCache.getInstance().put(uid,userByUid,10*1000L);
//            }
//            response = ConvertUtil.convert(userByUid, GetUserByUidResponse.class);
//            setUserByUidResponse(response,userByUid);
//        } catch (Exception e) {
//            log.error(e.getMessage(),e);
//        }
//        return response;
//    }

    private void setUserByUidResponse(GetUserByUidResponse response,AiUser aiUser){
        if (response == null || aiUser == null){
            return;
        }
        if (StringUtils.isNotBlank(aiUser.getNickName())){
            response.setName(aiUser.getNickName());
            response.setIsLogin(true);
        }
        if (StringUtils.isNotBlank(aiUser.getAvatarUrl())){
            response.setHeadPortrait(aiUser.getAvatarUrl());
        }
        //分享描述
        String shareDesc = ConfigUtil.getInstance().getConfig(ConfigModuleEnum.share.getModule(), "shareDesc");
        //设置分享描述
        response.setShareDesc(shareDesc);
        //观看广告视频描述
        String watchVideoDesc = ConfigUtil.getInstance().getConfig(ConfigModuleEnum.advertising.getModule(), "watchVideoDesc");
        response.setWatchVideoDesc(watchVideoDesc);

        RefObject<Boolean> isSignIn = new RefObject<>(false);
        //设置签到信息
        List<SignInDto> signInDtos = getSignInDtos(aiUser.getUid(),isSignIn);
        response.setIsSignIn(isSignIn.getArgvalue());
        response.setSignInList(signInDtos);
        //是否展示分享福利
        String welfareShare = ConfigUtil.getInstance().getConfig(ConfigModuleEnum.DEFAULT.getModule(), "welfareShare");
        if(welfareShare != null && welfareShare.equals("true")) {
            //超级管理员才展示
            String superAdmin = ConfigUtil.getInstance().getConfig(ConfigModuleEnum.DEFAULT.getModule(), "superAdmin");
            if (StringUtils.isNotBlank(superAdmin)) {
                String[] superAdminArr = superAdmin.split(",");
                List<String> superAdminList = new ArrayList<>(superAdminArr.length);
                //数组转list
                Collections.addAll(superAdminList, superAdminArr);
                if (superAdminList.contains(aiUser.getUid())) {
                    response.setWelfareShare(true);
                }
            }
        }

    }

    private List<SignInDto> getSignInDtos(String uid,RefObject<Boolean> isSignIn) {
        if (StringUtils.isBlank(uid)){
            return null;
        }
        //获取用户签到信息
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        List<String> dateList = new ArrayList<>();
        //大前天日期
        //String todayDateStrLt3 = LocalDate.now().minusDays(3).format(dateFormatter);
        //dateList.add(todayDateStrLt3);
        //前天日期
        String todayDateStrLt2 = LocalDate.now().minusDays(2).format(dateFormatter);
        dateList.add(todayDateStrLt2);
        //昨天日期
        String todayDateStrLt1 = LocalDate.now().minusDays(1).format(dateFormatter);
        dateList.add(todayDateStrLt1);
        //今天日期
        String todayDateStrLt0 = LocalDate.now().format(dateFormatter);
        dateList.add(todayDateStrLt0);

        List<AiUserSignIn> aiUserSignInList = aiUserSignInRepository.getUserSignInByUidDate(uid, dateList);
        Map<String, Boolean> signInMap = new HashMap<>();
        Map<String, AiUserSignIn> aiUserSignInMap = null;
        if (CollectionUtils.isNotEmpty(aiUserSignInList)) {
            //判断已签到是否包含今天
            boolean containsToday = aiUserSignInList.stream()
                    .map(AiUserSignIn::getDateStr) // 获取所有Person对象的name属性值组成的Stream
                    .anyMatch(x -> x.contains(todayDateStrLt0)); // 判断是否有name属性值包含指定字符串
            if (isSignIn != null && containsToday) {
                isSignIn.setArgvalue(true);
            }
            aiUserSignInMap = aiUserSignInList.stream().collect(Collectors.toMap(AiUserSignIn::getDateStr, v -> v, (k1, k2) -> k1));
        }
        for (int i = 0; i < dateList.size(); i++) {
            String date = dateList.get(i);
            if (aiUserSignInMap != null && aiUserSignInMap.get(date) != null && date.equals(aiUserSignInMap.get(date).getDateStr())){
                signInMap.put(date,true);
            }else{
                signInMap.put(date,false);
            }
        }
        List<SignInDto> signInDtoList = new ArrayList<>();
        String signInAdd = ConfigUtil.getInstance().getConfig(ConfigModuleEnum.integral.getModule(), "signInAdd");
        List<Integer> integralList = null;
        if (StringUtils.isNotBlank(signInAdd)) {
            integralList = Arrays.stream(signInAdd.split(",")).map(Integer::parseInt).collect(Collectors.toList());
        }
        //1.看今天有没有签到
        if (signInMap.get(todayDateStrLt0)){
            //今天已签到场景
            if (signInMap.get(todayDateStrLt1)){
                if (signInMap.get(todayDateStrLt2)){
                    for (int i = 0; i < dateList.size(); i++) {
                        SignInDto signInDto = new SignInDto();
                        signInDto.setSignDateNumber(i + 1);
                        signInDto.setIsSignIn(true);
                        if (CollectionUtils.isNotEmpty(integralList)) {
                            signInDto.setIntegral(integralList.get(i));
                        }
                        signInDto.setDesc("已完成");
                        signInDtoList.add(signInDto);
                    }
                }else{
                    for (int i = 0; i < dateList.size(); i++) {
                        SignInDto signInDto = new SignInDto();
                        signInDto.setSignDateNumber(i + 1);
                        signInDto.setDesc("已完成");
                        signInDto.setIsSignIn(true);
                        if (CollectionUtils.isNotEmpty(integralList)) {
                            signInDto.setIntegral(integralList.get(i));
                        }
                        if (i == dateList.size() - 1){
                            signInDto.setDesc("第3天");
                            signInDto.setIsSignIn(false);
                        }
                        signInDtoList.add(signInDto);
                    }
                }
            } else {
                for (int i = 0; i < dateList.size(); i++) {
                    SignInDto signInDto = new SignInDto();
                    signInDto.setSignDateNumber(i + 1);
                    signInDto.setDesc("已完成");
                    signInDto.setIsSignIn(true);
                    if (CollectionUtils.isNotEmpty(integralList)) {
                        signInDto.setIntegral(integralList.get(i));
                    }
                    if (i == 1 || i == 2){
                        signInDto.setDesc("第" + (i + 1) + "天");
                        signInDto.setIsSignIn(false);
                    }
                    signInDtoList.add(signInDto);
                }
            }
        ///////////////////////////////////
        } else {
            //今天未签到场景
            if (signInMap.get(todayDateStrLt1)){
                if (signInMap.get(todayDateStrLt2)){
                    for (int i = 0; i < dateList.size(); i++) {
                        SignInDto signInDto = new SignInDto();
                        signInDto.setSignDateNumber(i + 1);
                        signInDto.setDesc("已完成");
                        signInDto.setIsSignIn(true);
                        if (CollectionUtils.isNotEmpty(integralList)) {
                            signInDto.setIntegral(integralList.get(i));
                        }
                        if (i == 2){
                            signInDto.setDesc("第3天");
                            signInDto.setIsSignIn(false);
                        }
                        signInDtoList.add(signInDto);
                    }
                }else{
                    for (int i = 0; i < dateList.size(); i++) {
                        SignInDto signInDto = new SignInDto();
                        signInDto.setSignDateNumber(i + 1);
                        signInDto.setIsSignIn(false);
                        if (CollectionUtils.isNotEmpty(integralList)) {
                            signInDto.setIntegral(integralList.get(i));
                        }
                        if (i == 0) {
                            signInDto.setDesc("已完成");
                            signInDto.setIsSignIn(true);
                        }else if(i == 1){
                            signInDto.setDesc("第2天");
                        }else{
                            signInDto.setDesc("第3天");
                        }
                        signInDtoList.add(signInDto);
                    }
                }
            }else{
                for (int i = 0; i < dateList.size(); i++) {
                    SignInDto signInDto = new SignInDto();
                    signInDto.setSignDateNumber(i + 1);
                    signInDto.setIsSignIn(false);
                    if (CollectionUtils.isNotEmpty(integralList)) {
                        signInDto.setIntegral(integralList.get(i));
                    }
                    if (i == 0){
                        signInDto.setDesc("待签到");
                    }else {
                        signInDto.setDesc("第" + (i + 1) + "天");
                    }
                    signInDtoList.add(signInDto);
                }
            }
        }
        return signInDtoList;
    }

    /**
     * 根据openid获取用户信息
     * @param openId
     * @return
     */
    public GetUserByOpenIdResponse getUserByOpenId(String openId) {
        AiUser userByOpenId = aiUserRepository.getUserByOpenId(openId);
        GetUserByOpenIdResponse convert = ConvertUtil.convert(userByOpenId, GetUserByOpenIdResponse.class);
        return convert;
    }


    public LoginResponse login(LoginRequest request) {
        LoginResponse response = new LoginResponse();
        if (request == null || StringUtils.isBlank(request.getNickName()) || StringUtils.isBlank(request.getUid())){
            response.setCode(1);
            response.setMsg("登陆失败");
            return response;
        }
        AiUser userByUid = aiUserRepository.getUserByUid(request.getUid());
        if (userByUid == null){
            response.setCode(1);
            response.setMsg("uid不存在");
            return response;
        }
        Long id = userByUid.getId();
        userByUid = new AiUser();
        userByUid.setId(id);
        userByUid.setNickName(request.getNickName());
//        if (StringUtils.isNotBlank(request.getAvatarUrl()) && !request.getAvatarUrl().startsWith("wxfile")) {
//            userByUid.setAvatarUrl(request.getAvatarUrl());
//        }
        userByUid.setAvatarUrl(request.getAvatarUrl());
        userByUid.setLanguage(request.getLanguage());
        int update = aiUserRepository.updateByPrimaryKeySelective(userByUid);
        if (update <= 0){
            response.setCode(1);
            response.setMsg("登陆失败");
            return response;
        }
        //删除缓存
        //TimeExpiredPoolCache.getInstance().remove(request.getUid());
        return response;
    }

    /**
     * 反馈和建议
     * @param request
     * @return
     */
    public FeedbackResponse feedback(FeedbackRequest request) {
        FeedbackResponse response = new FeedbackResponse();
        if (StringUtils.isBlank(request.getContent())){
            response.setCode(1);
            response.setMsg("请填写内容");
            return response;
        }
        Long id = 0L;
        try {
            FeedbackSuggest feedbackSuggest = new FeedbackSuggest();
            feedbackSuggest.setUid(request.getUid());
            feedbackSuggest.setContent(request.getContent());
            feedbackSuggest.setContact(request.getContact());
            feedbackSuggestRepository.insertSelective(feedbackSuggest);
            id = feedbackSuggest.getId();
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        String feedbackToEmails = ConfigUtil.getInstance().getConfig(ConfigModuleEnum.email.getModule(), "feedbackToEmails");
        if (StringUtils.isNotBlank(feedbackToEmails)) {
            String[] feedbackToEmailsArray = feedbackToEmails.split(",");
            List<String> toEmails = new ArrayList<>(feedbackToEmailsArray.length);
            //数组转list
            Collections.addAll(toEmails, feedbackToEmailsArray);
            //发送邮件
            emailClient.send(request.getUid() + "的反馈和建议", "id：" + id + "，联系方式：" + request.getContact() + "，内容：" + request.getContent(), toEmails);
        }
        return response;
    }

    /**
     * @param type 1.使用说明，2.关于我们，3.隐私政策，4.用户协议
     * @return
     */
    public AboutResponse about(Integer type) {
        AboutResponse response = new AboutResponse();
        String content = null;
        if (type == 1) {
            //使用说明
            content = ConfigUtil.getInstance().getConfig(ConfigModuleEnum.DEFAULT.getModule(), "instructions");
        }else if (type == 2) {
            //关于我们
            content = ConfigUtil.getInstance().getConfig(ConfigModuleEnum.DEFAULT.getModule(), "aboutUs");
        }else if (type == 3) {
            //隐私政策
            content = ConfigUtil.getInstance().getConfig(ConfigModuleEnum.DEFAULT.getModule(), "privacyPolicy");
        }else if (type == 4) {
            //用户协议
            content = ConfigUtil.getInstance().getConfig(ConfigModuleEnum.DEFAULT.getModule(), "userAgreement");
        }
        response.setContent(content);
        return response;
    }

    /**
     * 签到接口
     * @param uid
     * @return
     */
    public SignInResponse signIn(String uid) {
        SignInResponse response = new SignInResponse();
        if (StringUtils.isBlank(uid)){
            return response;
        }
        String dateStr = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        AiUserSignIn aiUserSignIn = new AiUserSignIn();
        aiUserSignIn.setUid(uid);
        aiUserSignIn.setDateStr(dateStr);
        List<AiUserSignIn> list = aiUserSignInRepository.select(aiUserSignIn);
        if (CollectionUtils.isNotEmpty(list)){
            response.setCode(1);
            response.setMsg("今天已签到");
            return response;
        }
        int insertSelective = aiUserSignInRepository.insertSelective(aiUserSignIn);
        if (insertSelective <= 0){
            response.setCode(1);
            response.setMsg("签到失败");
            return response;
        }

        AiUser signInUser = aiUserRepository.getUserByUid(uid);
        if (signInUser == null){
            return response;
        }
        //获取签到信息
        List<SignInDto> signInDtos = getSignInDtos(signInUser.getUid(),null);
        if (CollectionUtils.isEmpty(signInDtos)){
            return response;
        }
        //获取刚刚签到的数据
        SignInDto signInDto = null;
        for (int i = signInDtos.size() - 1; i >= 0; i--) {
            if (signInDtos.get(i).getIsSignIn()) {
                signInDto = signInDtos.get(i);
                break;
            }
        }
        if (signInDto != null && signInDto.getIntegral() != null) {
            //签到加积分
            signInUser.setIntegral(signInUser.getIntegral() + signInDto.getIntegral());
            aiUserRepository.updateByPrimaryKeySelective(signInUser);
        }
        return response;
    }

    /**
     * 获取福利状态
     * @param uid
     * @return
     */
    public GetWelfareStatusResponse getWelfareStatus(String uid) {
        GetWelfareStatusResponse response = new GetWelfareStatusResponse();
        response.setStatus(0);
        String welfareShareTitle = ConfigUtil.getInstance().getConfig(ConfigModuleEnum.DEFAULT.getModule(), "welfareShareTitle");
        String welfareShareImg = ConfigUtil.getInstance().getConfig(ConfigModuleEnum.DEFAULT.getModule(), "welfareShareImg");
        response.setWelfareShareTitle(welfareShareTitle);
        response.setWelfareShareImg(welfareShareImg);
        if (StringUtils.isBlank(uid)){
            response.setCode(1);
            response.setMsg("新用户请移步首页获取登录态再来领取");
            return response;
        }
        String welfare = ConfigUtil.getInstance().getConfig(ConfigModuleEnum.integral.getModule(), "welfare");
        if (StringUtils.isBlank(welfare)){
            return response;
        }
        String[] split = welfare.split(",");
        //积分
        String integral = split[0];
        //活动号
        String activityNo = split[1];
        //截止时间
        String endTimeStr = split[2];
        long dateTimestamp = CommonUtil.getDateTimeTimestamp(endTimeStr);
        long currentTimeMillis = System.currentTimeMillis();
        if (currentTimeMillis > dateTimestamp){
            return response;
        }
        AiUser userByUid = aiUserRepository.getUserByUid(uid);
        if (userByUid == null){
            response.setCode(1);
            response.setMsg("用户不存在");
            return response;
        }
        RBucket<Integer> welfareBucket = redissonClient.getBucket(CommonUtil.getWelfareBucketKey(activityNo,uid));
        Integer status = welfareBucket.get();
        if (status != null && status == 2){
            //已领取
            response.setStatus(2);
        }else {
            response.setStatus(1);
        }
        response.setIntegral(Integer.parseInt(integral));
        response.setIntegralDesc("免费领取" + integral + "积分");
        response.setEndTime(endTimeStr);
        return response;
    }

    /**
     * 获取福利
     * @param uid
     * @return
     */
    public ReceiveWelfareResponse receiveWelfare(String uid) {
        ReceiveWelfareResponse response = new ReceiveWelfareResponse();
        response.setResult(false);
        if (StringUtils.isBlank(uid)){
            response.setCode(1);
            response.setMsg("新用户请移步首页获取登录态再来领取");
            return response;
        }
        String welfare = ConfigUtil.getInstance().getConfig(ConfigModuleEnum.integral.getModule(), "welfare");
        if (StringUtils.isBlank(welfare)){
            return response;
        }
        String[] split = welfare.split(",");
        //积分
        String integral = split[0];
        //活动号
        String activityNo = split[1];
        //截止时间
        String endTimeStr = split[2];
        long dateTimestamp = CommonUtil.getDateTimeTimestamp(endTimeStr);
        long currentTimeMillis = System.currentTimeMillis();
        if (currentTimeMillis > dateTimestamp){
            return response;
        }
        AiUser userByUid = aiUserRepository.getUserByUid(uid);
        if (userByUid == null){
            response.setCode(1);
            response.setMsg("用户不存在");
            return response;
        }
        RBucket<Integer> welfareBucket = redissonClient.getBucket(CommonUtil.getWelfareBucketKey(activityNo,uid));
        Integer status = welfareBucket.get();
        if (status != null && status == 2){
            return response;
        }
        int updateIntegral = aiUserRepository.updateIntegral(uid, Integer.parseInt(integral));
        if (updateIntegral > 0){
            log.info(uid + " 领取了福利积分");
            //领取成功
            welfareBucket.set(2,1, TimeUnit.DAYS);
            response.setResult(true);
        }
        return response;
    }

    /**
     * 获取当天新用户
     * @return
     */
    public GetCurDateUserResponse getCurDateUser() {
        GetCurDateUserResponse response = new GetCurDateUserResponse();
        List<AiUser> userList = aiUserRepository.getCurDateUser();
        List<GetCurDateUserDto> list = ConvertUtil.convertList(userList,GetCurDateUserDto.class);
        if (CollectionUtils.isNotEmpty(list)){
            response.setTotal(list.size());
        }else{
            response.setTotal(0);
        }
        response.setList(list);
        return response;
    }

    /**
     * 新增用户量发送邮件
     */
    public void sendEmailCurDateUser(){
        List<AiUser> userList = aiUserRepository.getCurDateUser();
        if (CollectionUtils.isEmpty(userList)){
            return;
        }
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("总数 -> ").append(userList.size()).append("\r\n\r\n");
        for (AiUser curDateUser : userList){
            stringBuilder.append("id：").append(curDateUser.getId()).append("\r\n");
            stringBuilder.append("uid：").append(curDateUser.getUid()).append("\r\n");
            stringBuilder.append("integral：").append(curDateUser.getIntegral()).append("\r\n");
            stringBuilder.append("shareUid：").append(curDateUser.getShareUid()).append("\r\n");
            String dateStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(curDateUser.getCreateTime());
            stringBuilder.append("createTime：").append(dateStr).append("\r\n\r\n");
        }
        String feedbackToEmails = ConfigUtil.getInstance().getConfig(ConfigModuleEnum.email.getModule(), "feedbackToEmails");
        if (StringUtils.isNotBlank(feedbackToEmails)) {
            String[] feedbackToEmailsArray = feedbackToEmails.split(",");
            List<String> toEmails = new ArrayList<>(feedbackToEmailsArray.length);
            //数组转list
            Collections.addAll(toEmails, feedbackToEmailsArray);
            //发送邮件
            emailClient.send( "新增用户统计", stringBuilder.toString(), toEmails);
        }
    }
}
